package ru.spb.osll.myfit.server.execute;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;

import org.apache.log4j.Logger;

public class TestResultMetadataDao {
  private Logger log = Logger.getLogger(getClass());

  public Map<String, String> load(InputStream stream) throws IOException {
    Properties props = new Properties();
    try {
      props.loadFromXML(stream);
    } catch (IOException e) {
      log.error("Failed to load test result metadata", e);
      throw e;
    }
    TreeMap<String, String> metadata = new TreeMap<String, String>();
    for (Object key : props.keySet()) {
      metadata.put(key.toString(), props.get(key).toString());
    }

    return metadata;
  }

  public Map<String, String> saveOld(Map<String, String> metadata, OutputStream stream) throws IOException {
    Properties props = new Properties();
    for (String key : metadata.keySet()) {
      props.put(key, metadata.get(key));
    }
    try {
      props.storeToXML(stream, null);
    } catch (IOException e) {
      log.error("Failed to save test result metadata", e);
      throw e;
    }

    return metadata;
  }

  public Map<String, String> save(Map<String, String> metadata, OutputStream stream) throws IOException {
    try {
      stream.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes());
      stream.write("<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">\n".getBytes());
      stream.write("<properties>\n".getBytes());
      stream.write("<comment/>\n".getBytes());
      for (String key : metadata.keySet()) {
        stream.write(("<entry key=\"" + key + "\">" + metadata.get(key) + "</entry>\n").getBytes());
      }
      stream.write("</properties>\n".getBytes());
      stream.flush();
    } catch (IOException e) {
      log.error("Failed to save test result metadata", e);
      throw e;
    }

    return metadata;
  }
}
